<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import JSZip from 'jszip'
import * as mars3d from 'mars3d'
// @ts-ignore
import { geoJSONToKml } from '../utils/conver/geoJSONToKml'
// @ts-ignore
import FacadeWaylineEditor from './FacadeWaylineEditor.vue'

interface WaylineItem {
  id: string
  name: string
  createdAt: number
  isFacade?: boolean  // 标记是否为立面航线
}

interface FacadeParams {
  minHeight: number    // 最低高度（米）
  maxHeight: number    // 最高高度（米）
  verticalInterval: number  // 垂直/水平间隔（米）
  lineSegmentId: string     // 关联的KML线段ID
  direction: 'horizontal' | 'vertical'  // 航线方向
}

const items = ref<WaylineItem[]>([])
const visibleMap = ref<Record<string, boolean>>({})
const layers = new Map<string, mars3d.layer.GraphicLayer>()

// 立面航线相关状态
const showFacadeEditor = ref(false)
const currentFacadeSegment = ref<any>(null)
const facadeParams = ref<FacadeParams>({
  minHeight: 10,
  maxHeight: 50,
  verticalInterval: 5,
  lineSegmentId: '',
  direction: 'vertical'  // 默认垂直方向
})
const facadePreviewLayer = ref<any>(null)

function load() {
  try {
    const raw = localStorage.getItem('wayLineList')
    items.value = raw ? JSON.parse(raw) : []
  } catch {
    items.value = []
  }
  // 同步可见性持久化
  try {
    const visRaw = localStorage.getItem('wayLineVisibleMap')
    visibleMap.value = visRaw ? JSON.parse(visRaw) : {}
  } catch {
    visibleMap.value = {}
  }
  // 应用可见性
  items.value.forEach((it) => applyVisibility(it.id, !!visibleMap.value[it.id]))
}

function saveVisibility() {
  localStorage.setItem('wayLineVisibleMap', JSON.stringify(visibleMap.value))
}

function open(item: WaylineItem) {
  console.log('[ImportList] 打开航线编辑:', item)
  const wl = getWaylineData(item.id)
  console.log('[ImportList] 获取到的原始数据:', wl)
  
  if (!wl) {
    console.error('[ImportList] 未找到航线数据，id:', item.id)
    console.log('[ImportList] localStorage 中的键:', `wayLine:${item.id}`)
    return
  }
  
  const lower = (item.name || '').toLowerCase()
  const isKMZ = /\.kmz$/.test(lower)
  const isKML = /\.kml$/.test(lower)
  const isFlightPanel = isKML && !isKMZ
  
  console.log('[ImportList] 文件类型判断:', { isKML, isKMZ, isFlightPanel, fileName: item.name })
  
  const payload = isFlightPanel ? convertLayerDataToWaylineFormat(wl) : wl
  console.log('[ImportList] 转换后的数据:', payload)
  
  const eventDetail = { 
    wayline: payload, 
    id: item.id, 
    name: item.name, 
    panel: isFlightPanel ? 'flight' : 'dji', 
    isFlightPanel 
  }
  console.log('[ImportList] 发送事件 wayline:openEditor，详情:', eventDetail)
  
  window.dispatchEvent(new CustomEvent('wayline:openEditor', { detail: eventDetail }))
}

// 调试辅助函数：检查 localStorage 中的所有航线数据
function debugListAllWaylines() {
  console.log('[DEBUG] 检查所有航线数据:')
  console.log('[DEBUG] 航线列表:', items.value)
  items.value.forEach(item => {
    const key = `wayLine:${item.id}`
    const raw = localStorage.getItem(key)
    console.log(`[DEBUG] ${key}:`, raw ? JSON.parse(raw) : 'null')
  })
}
// 暴露到 window 方便调试
;(window as any).debugListAllWaylines = debugListAllWaylines

// 参考 flight-control/KmlUploadComponent.vue 的转换逻辑，
// 将普通KML/GeoJSON结构转换为最小可编辑航线（飞控侧）
function convertLayerDataToWaylineFormat(layerData: any) {
  console.log('[convertLayerData] 输入数据:', layerData)
  
  if (!layerData) {
    console.warn('[convertLayerData] 数据为空')
    return layerData
  }
  
  // 若已包含wayline结构，直接返回
  if (layerData.wayline) {
    console.log('[convertLayerData] 已包含wayline结构，直接返回')
    return layerData.wayline
  }
  
  // 如果已经是完整的航线格式（包含 Placemark 和 positionsArr），直接返回
  if (layerData.Placemark && layerData.positionsArr) {
    console.log('[convertLayerData] 已是完整航线格式，直接返回')
    return layerData
  }

  const waylineData = {
    author: 'user',
    createTime: Date.now(),
    updateTime: Date.now(),
    flyToWaylineMode: 'safely',
    finishAction: 'goHome',
    droneInfo: { droneEnumValue: '67', droneSubEnumValue: '0' },
    payloadInfo: { payloadEnumValue: '53', payloadSubEnumValue: '0', payloadPositionIndex: '0' },
    autoFlightSpeed: String(layerData?.autoFlightSpeed || 10),
    globalHeight: String(layerData?.globalHeight || 100),
    takeOffRefPoint: layerData?.takeOffRefPoint || '',
    takeOffRefPointAGLHeight: layerData?.takeOffRefPointAGLHeight ?? 20,
    takeOffSecurityHeight: layerData?.takeOffSecurityHeight ?? 20,
    payloadParam: { imageFormat: 'wide,zoom' },
    Placemark: [] as any[],
    positionsArr: [] as number[][],
    distance: 0
  }

  if (layerData.geojson && layerData.geojson.features) {
    console.log('[convertLayerData] 从 GeoJSON features 提取航点')
    const features = layerData.geojson.features
    const placemarks: any[] = []
    const positions: number[][] = []
    
    features.forEach((feature: any, index: number) => {
      if (feature.geometry && feature.geometry.type === 'Point') {
        const coords = feature.geometry.coordinates
        if (coords && coords.length >= 2) {
          placemarks.push({
            Point: { coordinates: `${coords[0]},${coords[1]}` },
            index: index.toString(),
            useGlobalHeight: '1',
            ellipsoidHeight: String(coords[2] || 100),
            height: coords[2] || 100,
            useGlobalSpeed: '1',
            waypointSpeed: String(layerData?.autoFlightSpeed || 10),
            useGlobalHeadingParam: '1',
            waypointHeadingParam: {
              waypointHeadingMode: 'followWayline',
              waypointHeadingAngle: '0',
              waypointHeadingPathMode: 'followBadArc',
              waypointPoiPoint: '0,0,0',
              waypointHeadingPoiIndex: '0'
            },
            useGlobalTurnParam: '1',
            waypointTurnParam: { waypointTurnMode: 'coordinateTurn', waypointTurnDampingDist: '0.2' },
            useStraightLine: '1',
            gimbalPitchAngle: 0,
            actionGroup: []
          })
          positions.push([Number(coords[0]), Number(coords[1]), Number(coords[2] || 100)])
        }
      }
    })
    
    ;(waylineData as any).Placemark = placemarks
    ;(waylineData as any).positionsArr = positions
    console.log('[convertLayerData] 提取完成，航点数量:', positions.length)
  } else {
    console.warn('[convertLayerData] 未找到 geojson.features，无法提取航点')
  }
  
  console.log('[convertLayerData] 转换后的航线数据:', waylineData)
  return waylineData
}

function remove(item: WaylineItem) {
  // 本地存储中删除
  localStorage.removeItem(`wayLine:${item.id}`)
  items.value = items.value.filter(i => i.id !== item.id)
  localStorage.setItem('wayLineList', JSON.stringify(items.value))
  // 可见性与图层清理
  delete visibleMap.value[item.id]
  saveVisibility()
  const layer = layers.get(item.id)
  const map: any = (window as any).map
  if (layer && map) {
    try { map.removeLayer(layer) } catch {}
  }
  // 兜底：尝试移除任何名称匹配的图层（防止首次导入未被layers表记录的残留图层）
  try {
    const targetName = `wayline:${item.name}`
    if (map?.getLayers && typeof map.getLayers === 'function') {
      const all = map.getLayers()
      try { all.forEach((l: any) => { if (l?.options?.name === targetName) { try { map.removeLayer(l) } catch {} } }) } catch {}
    }
    // 某些版本可通过内部集合访问
    const inner = map?.layers?.layers
    if (Array.isArray(inner)) {
      inner.forEach((l: any) => { if (l?.options?.name === targetName) { try { map.removeLayer(l) } catch {} } })
    }
    // 遍历可能的layer集合接口
    if (typeof map.eachLayer === 'function') {
      try { map.eachLayer((l: any) => { if (l?.options?.name === targetName) { try { map.removeLayer(l) } catch {} } }) } catch {}
    }
  } catch {}
  layers.delete(item.id)
}

function getWaylineData(id: string): any | null {
  const raw = localStorage.getItem(`wayLine:${id}`)
  if (!raw) return null
  try { return JSON.parse(raw) } catch { return null }
}

function ensureLayer(id: string, name: string, wl: any): mars3d.layer.GraphicLayer | null {
  const existing = layers.get(id)
  if (existing) return existing
  const map: mars3d.Map | undefined = (window as any).map
  if (!map) return null
  const layer = new mars3d.layer.GraphicLayer({ name: `wayline:${name}`, show: true })
  map.addLayer(layer)
  // 绘制点
  const positions = Array.isArray(wl?.positionsArr) ? wl.positionsArr : []
  positions.forEach((pos: number[], idx: number) => {
    if (!Array.isArray(pos) || pos.length < 2) return
    const [lng, lat, alt] = [Number(pos[0]||0), Number(pos[1]||0), Number(pos[2]||0)]
    new mars3d.graphic.PointEntity({
      position: [lng, lat, alt],
      attr: { name: `航点${idx + 1}`, index: idx },
      style: { color: '#00ffff', pixelSize: 8, clampToGround: false }
    }).addTo(layer)
  })
  // 绘制线
  if (positions.length > 1) {
    const line = new mars3d.graphic.PolylineEntity({
      positions,
      name: 'wayline',
      style: { width: 3, color: '#1a9850' }
    })
    layer.addGraphic(line)
  }
  layers.set(id, layer)
  return layer
}

function applyVisibility(id: string, visible: boolean) {
  const item = items.value.find(i => i.id === id)
  if (!item) return
  const wl = getWaylineData(id)
  if (!wl) return
  const layer = ensureLayer(id, item.name, wl)
  if (!layer) return
  layer.show = visible
}

function onToggleItem(id: string, next: boolean) {
  visibleMap.value[id] = next
  saveVisibility()
  applyVisibility(id, next)
}

function waylineToGeoJSON(from: any) {
  console.log('from', from)
  const features: any[] = []
  const positions = Array.isArray(from?.positionsArr) ? from.positionsArr : []
  const placemarks = Array.isArray(from?.Placemark) ? from.Placemark : []
  positions.forEach((pos: number[], idx: number) => {
    if (!Array.isArray(pos) || pos.length < 2) return
    const props = { name: `航点${idx + 1}`, index: idx, ...(placemarks[idx] || {}) }
    features.push({ type: 'Feature', geometry: { type: 'Point', coordinates: [pos[0], pos[1], pos[2] || 0] }, properties: props })
  })
  if (positions.length > 1) {
    const lineProps = {
      type: 'wayline',
      globalHeight: from?.globalHeight,
      autoFlightSpeed: from?.autoFlightSpeed,
      flyToWaylineMode: from?.flyToWaylineMode,
      finishAction: from?.finishAction,
      waylineCoordinateSysParam: from?.waylineCoordinateSysParam,
      globalWaypointTurnMode: from?.globalWaypointTurnMode,
      globalWaypointHeadingParam: from?.globalWaypointHeadingParam,
    }
    features.push({ type: 'Feature', geometry: { type: 'LineString', coordinates: positions }, properties: lineProps })
  }
  return { type: 'FeatureCollection', features }
}

function download(filename: string, blob: Blob) {
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  URL.revokeObjectURL(url)
  a.remove()
}

function exportNormalKml(item: WaylineItem) {
  const wl = getWaylineData(item.id)
  if (!wl) return
  const geojson = waylineToGeoJSON(wl)
  const kml = geoJSONToKml(geojson, { documentName: item.name })
  download(`${item.name}.kml`, new Blob([kml], { type: 'application/vnd.google-earth.kml+xml' }))
}

function exportFlightKml(item: WaylineItem) {
  // 基于普通KML导出，ExtendedData中已包含飞控参数（properties写入）
  exportNormalKml(item)
}

async function exportDjiKmz(item: WaylineItem) {
  const wl = getWaylineData(item.id)
  if (!wl) return
  const geojson = waylineToGeoJSON(wl)
  const kml = geoJSONToKml(geojson, { documentName: item.name })
  const zip = new JSZip()
  zip.file('doc.kml', kml)
  const content = await zip.generateAsync({ type: 'blob' })
  download(`${item.name}.kmz`, content)
}

// ========== 立面航线功能 ==========

// 导入立面KML（只包含线段）
async function importFacadeKml(file: File) {
  try {
    console.log('[Facade] 开始导入立面KML:', file.name)
    
    // 检查文件大小（防止过大文件）
    if (file.size > 10 * 1024 * 1024) {
      alert('文件过大，请选择小于10MB的KML文件')
      return
    }
    
    // 读取文件内容
    const text = await file.text()
    
    if (!text || text.trim().length === 0) {
      alert('文件内容为空')
      return
    }
    
    // 解析XML
    const parser = new DOMParser()
    const xmlDoc = parser.parseFromString(text, 'text/xml')
    
    // 检查解析错误
    const parserError = xmlDoc.getElementsByTagName('parsererror')
    if (parserError && parserError.length > 0) {
      const errorText = parserError[0]?.textContent || '未知错误'
      console.error('[Facade] XML解析错误:', errorText)
      alert('KML文件格式错误，无法解析')
      return
    }
    
    // 解析KML中的LineString
    const lineStrings = xmlDoc.getElementsByTagName('LineString')
    if (!lineStrings || lineStrings.length === 0) {
      alert('KML中未找到线段，请确保导入的是包含LineString的KML文件')
      return
    }
    
    // 获取第一个线段的坐标
    const firstLineString = lineStrings[0]
    if (!firstLineString) {
      alert('无法获取线段元素')
      return
    }
    
    const coordElement = firstLineString.getElementsByTagName('coordinates')[0]
    const coordinates = coordElement?.textContent?.trim()
    if (!coordinates) {
      alert('无法解析线段坐标')
      return
    }
    
    console.log('[Facade] 原始坐标字符串:', coordinates.substring(0, 200))
    
    // 解析坐标点
    const points: number[][] = []
    const coordParts = coordinates.split(/\s+/).filter(s => s.trim().length > 0)
    
    for (const coord of coordParts) {
      try {
        const parts = coord.trim().split(',')
        if (parts.length < 2) continue
        
        const lngStr = parts[0]
        const latStr = parts[1]
        if (!lngStr || !latStr) continue
        
        const lng = parseFloat(lngStr)
        const lat = parseFloat(latStr)
        const alt = parts[2] ? parseFloat(parts[2]) : 0
        
        // 验证坐标范围
        if (isNaN(lng) || isNaN(lat) || 
            lng < -180 || lng > 180 || 
            lat < -90 || lat > 90) {
          console.warn('[Facade] 跳过无效坐标:', coord)
          continue
        }
        
        points.push([lng, lat, alt])
      } catch (e) {
        console.warn('[Facade] 解析坐标失败:', coord, e)
      }
    }
    
    if (points.length < 2) {
      alert(`线段至少需要2个有效点，当前解析到${points.length}个点`)
      return
    }
    
    console.log('[Facade] 成功解析线段点数:', points.length)
    console.log('[Facade] 首尾点:', points[0], points[points.length - 1])
    
    // 保存线段数据
    const segmentId = `facade-segment-${Date.now()}`
    currentFacadeSegment.value = {
      id: segmentId,
      name: file.name.replace(/\.kml$/i, ''),
      points
    }
    facadeParams.value.lineSegmentId = segmentId
    
    // 等待一帧确保状态更新
    await new Promise(resolve => setTimeout(resolve, 100))
    
    // 在地图上绘制线段预览
    const drawSuccess = await drawFacadeSegmentPreview(points)
    
    if (!drawSuccess) {
      console.warn('[Facade] 地图预览绘制失败，但继续打开编辑器')
    }
    
    // 打开立面编辑器
    showFacadeEditor.value = true
    
    console.log('[Facade] 导入完成')
    
  } catch (err) {
    console.error('[Facade] 导入失败:', err)
    const errorMsg = err instanceof Error ? err.message : String(err)
    alert(`导入立面KML失败：${errorMsg}\n\n请检查文件格式是否正确。`)
    
    // 清理状态
    currentFacadeSegment.value = null
    showFacadeEditor.value = false
  }
}

// 在地图上绘制线段预览
async function drawFacadeSegmentPreview(points: number[][]): Promise<boolean> {
  try {
    console.log('[Facade] 开始绘制预览，点数:', points.length)
    
    const map: any = (window as any).map
    if (!map) {
      console.warn('[Facade] 地图实例未找到')
      return false
    }
    
    // 检查地图是否已初始化
    if (!map.addLayer || typeof map.addLayer !== 'function') {
      console.warn('[Facade] 地图未完全初始化')
      return false
    }
    
    // 安全清除旧的预览图层
    if (facadePreviewLayer.value) {
      try {
        console.log('[Facade] 清除旧预览图层')
        // 先清除图层上的所有图形
        if (facadePreviewLayer.value.clear) {
          facadePreviewLayer.value.clear()
        }
        // 再移除图层
        if (map.removeLayer) {
          map.removeLayer(facadePreviewLayer.value, true)
        }
        facadePreviewLayer.value = null
      } catch (e) {
        console.warn('[Facade] 清除旧图层时出错:', e)
      }
    }
    
    // 等待一帧确保清理完成
    await new Promise(resolve => setTimeout(resolve, 50))
    
    // 验证mars3d是否可用
    if (!mars3d || !mars3d.layer || !mars3d.layer.GraphicLayer) {
      console.error('[Facade] mars3d未正确加载')
      return false
    }
    
    // 创建新的预览图层
    try {
      console.log('[Facade] 创建新预览图层')
      facadePreviewLayer.value = new mars3d.layer.GraphicLayer({ 
        name: 'facade-preview', 
        show: true
      })
      
      if (!facadePreviewLayer.value) {
        console.error('[Facade] 创建图层失败')
        return false
      }
      
      map.addLayer(facadePreviewLayer.value)
      console.log('[Facade] 图层添加成功')
    } catch (e) {
      console.error('[Facade] 创建或添加图层失败:', e)
      facadePreviewLayer.value = null
      return false
    }
    
    // 绘制原始线段
    try {
      console.log('[Facade] 绘制基准线')
      const line = new mars3d.graphic.PolylineEntity({
        positions: points,
        name: '立面基准线',
        style: { 
          width: 3, 
          color: '#ff0000', 
          clampToGround: true,
          opacity: 0.8
        }
      })
      
      facadePreviewLayer.value.addGraphic(line)
      
      // 标记关键点（起点、终点、中间点）
      const pointsToMark = [
        { idx: 0, label: '起点', color: '#00ff00' },
        { idx: points.length - 1, label: '终点', color: '#ff0000' }
      ]
      
      // 如果点数较多，添加中间点标记
      if (points.length > 4) {
        const midIdx = Math.floor(points.length / 2)
        pointsToMark.push({ idx: midIdx, label: `中点`, color: '#ffff00' })
      }
      
      for (const { idx, label, color } of pointsToMark) {
        if (idx >= 0 && idx < points.length) {
          const pos = points[idx]
          if (pos && pos.length >= 2) {
            try {
              const point = new mars3d.graphic.PointEntity({
                position: pos,
                attr: { name: label },
                style: { 
                  color: color, 
                  pixelSize: 10, 
                  clampToGround: true,
                  outlineColor: '#ffffff',
                  outlineWidth: 2
                }
              })
              facadePreviewLayer.value.addGraphic(point)
            } catch (e) {
              console.warn(`[Facade] 绘制点${label}失败:`, e)
            }
          }
        }
      }
      
      // 尝试飞到线段位置（可选操作，失败不影响）
      try {
        if (line.flyTo && typeof line.flyTo === 'function') {
          await line.flyTo({ duration: 1 })
        } else if (map.flyToGraphic) {
          await map.flyToGraphic(line, { duration: 1 })
        }
      } catch (e) {
        console.warn('[Facade] 飞行到位置失败:', e)
      }
      
      console.log('[Facade] 预览绘制完成')
      return true
      
    } catch (e) {
      console.error('[Facade] 绘制图形失败:', e)
      // 清理失败的图层
      if (facadePreviewLayer.value && map.removeLayer) {
        try {
          map.removeLayer(facadePreviewLayer.value, true)
        } catch {}
        facadePreviewLayer.value = null
      }
      return false
    }
    
  } catch (error) {
    console.error('[Facade] 绘制预览时发生错误:', error)
    return false
  }
}

// 生成立面航线
function generateFacadeWayline(params?: FacadeParams) {
  // 支持从外部传入参数（来自组件）
  const effectiveParams = params || facadeParams.value
  
  if (!currentFacadeSegment.value) {
    alert('请先导入KML线段')
    return
  }
  
  const { points } = currentFacadeSegment.value
  const { minHeight, maxHeight, verticalInterval, direction } = effectiveParams
  
  if (minHeight >= maxHeight) {
    alert('最低高度必须小于最高高度')
    return
  }
  
  if (verticalInterval <= 0) {
    alert('间隔必须大于0')
    return
  }
  
  console.log('[Facade] 生成立面航线，参数:', effectiveParams)
  
  // 计算需要多少层（仅用于水平飞行）
  const layers = Math.ceil((maxHeight - minHeight) / verticalInterval) + 1
  
  if (direction === 'horizontal') {
    console.log('[Facade] 水平扫描层数:', layers)
  } else {
    console.log('[Facade] 垂直飞行模式 - 水平采样间隔:', verticalInterval, '米')
  }
  
  // 生成航点
  const waypoints: number[][] = []
  const placemarks: any[] = []
  
  let wpIndex = 0
  
  if (direction === 'vertical') {
    // 垂直方向：沿线段各点垂直爬升/下降（间隔是水平的）
    // 首先沿线段按水平间隔采样点
    const sampledPoints: number[][] = []
    
    // 计算线段总长度并采样
    if (points.length >= 2) {
      let totalDistance = 0
      const distances: number[] = [0]
      
      // 计算累积距离
      for (let i = 1; i < points.length; i++) {
        const p1 = points[i]
        const p0 = points[i-1]
        if (!p1 || !p0) continue
        
        const dx = p1[0] - p0[0]
        const dy = p1[1] - p0[1]
        const dist = Math.sqrt(dx * dx + dy * dy) * 111000 // 粗略转换为米
        totalDistance += dist
        distances.push(totalDistance)
      }
      
      // 按间隔采样
      const numSamples = Math.max(2, Math.ceil(totalDistance / verticalInterval))
      for (let i = 0; i < numSamples; i++) {
        const targetDist = (totalDistance / (numSamples - 1)) * i
        
        // 找到对应的线段
        let segmentIdx = 0
        for (let j = 0; j < distances.length - 1; j++) {
          const d1 = distances[j]
          const d2 = distances[j + 1]
          if (d1 !== undefined && d2 !== undefined && targetDist >= d1 && targetDist <= d2) {
            segmentIdx = j
            break
          }
        }
        
        // 插值计算点位置
        const d1 = distances[segmentIdx]
        const d2 = distances[segmentIdx + 1]
        const p1 = points[segmentIdx]
        const p2 = points[segmentIdx + 1]
        
        if (d1 === undefined || d2 === undefined || !p1 || !p2) continue
        
        const t = d2 > d1 ? (targetDist - d1) / (d2 - d1) : 0
        
        const lng = p1[0] + (p2[0] - p1[0]) * t
        const lat = p1[1] + (p2[1] - p1[1]) * t
        
        sampledPoints.push([lng, lat])
      }
    } else {
      sampledPoints.push(...points)
    }
    
    // 沿采样点垂直飞行（每个点只需最低和最高两个航点）
    sampledPoints.forEach((point: number[], pointIdx: number) => {
      const lng = point[0] ?? 0
      const lat = point[1] ?? 0
      
      // 奇数点从下往上，偶数点从上往下（之字形）
      const isAscending = pointIdx % 2 === 0
      
      if (isAscending) {
        // 从下往上：最低点 → 最高点
        waypoints.push([lng, lat, minHeight])
        placemarks.push(createPlacemark(lng, lat, minHeight, wpIndex))
        wpIndex++
        
        waypoints.push([lng, lat, maxHeight])
        placemarks.push(createPlacemark(lng, lat, maxHeight, wpIndex))
        wpIndex++
      } else {
        // 从上往下：最高点 → 最低点
        waypoints.push([lng, lat, maxHeight])
        placemarks.push(createPlacemark(lng, lat, maxHeight, wpIndex))
        wpIndex++
        
        waypoints.push([lng, lat, minHeight])
        placemarks.push(createPlacemark(lng, lat, minHeight, wpIndex))
        wpIndex++
      }
    })
  } else {
    // 水平方向：从下往上逐层水平飞行（间隔是垂直的）
    for (let layer = 0; layer < layers; layer++) {
      const height = minHeight + layer * verticalInterval
      
      // 奇数层正向，偶数层反向（之字形路径，节省时间）
      const layerPoints = layer % 2 === 0 ? [...points] : [...points].reverse()
      
      layerPoints.forEach((point) => {
        const [lng, lat] = point
        const position = [lng, lat, height]
        waypoints.push(position)
        
        placemarks.push(createPlacemark(lng, lat, height, wpIndex))
        wpIndex++
      })
    }
  }
  
  console.log('[Facade] 生成航点总数:', waypoints.length)
  
  // 创建航点辅助函数
  function createPlacemark(lng: number, lat: number, height: number, index: number) {
    return {
      Point: { coordinates: `${lng},${lat}` },
      index: index.toString(),
      useGlobalHeight: '0',
      ellipsoidHeight: String(height),
      height: height,
      useGlobalSpeed: '1',
      waypointSpeed: '5',
      useGlobalHeadingParam: '1',
      waypointHeadingParam: {
        waypointHeadingMode: 'followWayline',
        waypointHeadingAngle: '0',
        waypointHeadingPathMode: 'followBadArc',
        waypointPoiPoint: '0,0,0',
        waypointHeadingPoiIndex: '0'
      },
      useGlobalTurnParam: '1',
      waypointTurnParam: { waypointTurnMode: 'coordinateTurn', waypointTurnDampingDist: '0.2' },
      useStraightLine: '1',
      gimbalPitchAngle: 0,
      actionGroup: []
    }
  }
  
  // 构建完整的航线数据
  const waylineData = {
    author: 'user',
    createTime: Date.now(),
    updateTime: Date.now(),
    flyToWaylineMode: 'safely',
    finishAction: 'goHome',
    droneInfo: { droneEnumValue: '67', droneSubEnumValue: '0' },
    payloadInfo: { payloadEnumValue: '53', payloadSubEnumValue: '0', payloadPositionIndex: '0' },
    autoFlightSpeed: '5',
    globalHeight: String(minHeight),
    takeOffRefPoint: '',
    takeOffRefPointAGLHeight: 20,
    takeOffSecurityHeight: 20,
    waylineCoordinateSysParam: { heightMode: 'EGM96' },
    globalWaypointHeadingParam: { waypointHeadingMode: 'followWayline' },
    gimbalPitchMode: 'manual',
    globalWaypointTurnMode: 'coordinateTurn',
    payloadParam: { imageFormat: 'wide,zoom' },
    positionsArr: waypoints,
    Placemark: placemarks,
    distance: 0,
    duration: 0,
    facadeParams: { ...effectiveParams }  // 保存立面参数
  }
  
  // 保存到列表
  const itemId = `facade-${Date.now()}`
  const directionLabel = direction === 'vertical' ? '垂直飞行' : '水平飞行'
  const itemName = `立面_${directionLabel}_${currentFacadeSegment.value.name}_${minHeight}-${maxHeight}m`
  
  const newItem: WaylineItem = {
    id: itemId,
    name: itemName,
    createdAt: Date.now(),
    isFacade: true
  }
  
  // 保存到localStorage
  localStorage.setItem(`wayLine:${itemId}`, JSON.stringify(waylineData))
  items.value.unshift(newItem)
  localStorage.setItem('wayLineList', JSON.stringify(items.value))
  
  // 通知更新
  window.dispatchEvent(new Event('wayLineList:updated'))
  
  // 在地图上预览生成的航线
  previewFacadeWayline(waypoints)
  
  alert(`立面航线生成成功！\n航点数量：${waypoints.length}\n垂直层数：${layers}`)
}

// 预览生成的立面航线
function previewFacadeWayline(waypoints: number[][]) {
  const map: any = (window as any).map
  if (!map || !facadePreviewLayer.value) return
  
  // 清除预览图层中的旧内容（保留基准线）
  const graphics = facadePreviewLayer.value.graphics || []
  graphics.forEach((g: any, idx: number) => {
    if (idx > 0) {  // 保留第一个（基准线）
      try { facadePreviewLayer.value.removeGraphic(g) } catch {}
    }
  })
  
  // 绘制航线
  const line = new mars3d.graphic.PolylineEntity({
    positions: waypoints,
    name: '立面航线',
    style: { width: 2, color: '#00ffff' }
  })
  facadePreviewLayer.value.addGraphic(line)
  
  // 绘制航点
  waypoints.forEach((pos, idx) => {
    if (idx % 5 === 0) {  // 每5个点显示一个，避免太密集
      const point = new mars3d.graphic.PointEntity({
        position: pos,
        attr: { name: `航点${idx + 1}`, index: idx },
        style: { color: '#00ffff', pixelSize: 6, clampToGround: false }
      })
      facadePreviewLayer.value.addGraphic(point)
    }
  })
}

// 关闭立面编辑器
function closeFacadeEditor() {
  console.log('[Facade] 关闭编辑器')
  
  try {
    showFacadeEditor.value = false
    
    // 安全清除预览图层
    const map: any = (window as any).map
    if (facadePreviewLayer.value) {
      try {
        // 先清除图层上的所有图形
        if (facadePreviewLayer.value.clear && typeof facadePreviewLayer.value.clear === 'function') {
          console.log('[Facade] 清除图层图形')
          facadePreviewLayer.value.clear()
        }
        
        // 再移除图层
        if (map && map.removeLayer && typeof map.removeLayer === 'function') {
          console.log('[Facade] 移除预览图层')
          map.removeLayer(facadePreviewLayer.value, true)
        }
      } catch (e) {
        console.warn('[Facade] 清除预览图层时出错:', e)
      } finally {
        facadePreviewLayer.value = null
      }
    }
    
    // 清除线段数据
    currentFacadeSegment.value = null
    
    // 重置参数为默认值
    facadeParams.value = {
      minHeight: 10,
      maxHeight: 50,
      verticalInterval: 5,
      lineSegmentId: '',
      direction: 'vertical'
    }
    
    console.log('[Facade] 编辑器关闭完成')
  } catch (error) {
    console.error('[Facade] 关闭编辑器时发生错误:', error)
  }
}

// 触发文件选择
function triggerFacadeKmlImport() {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.kml'
  input.onchange = (e: any) => {
    const file = e.target.files?.[0]
    if (file) importFacadeKml(file)
  }
  input.click()
}

// ========== 原有功能 ==========

onMounted(load)
function onUpdated() { load() }
onMounted(() => window.addEventListener('wayLineList:updated', onUpdated))
onBeforeUnmount(() => {
  console.log('[ImportList] 组件卸载，清理资源')
  window.removeEventListener('wayLineList:updated', onUpdated)
  
  // 清理立面预览图层
  if (facadePreviewLayer.value) {
    try {
      const map: any = (window as any).map
      if (facadePreviewLayer.value.clear) {
        facadePreviewLayer.value.clear()
      }
      if (map && map.removeLayer) {
        map.removeLayer(facadePreviewLayer.value, true)
      }
    } catch (e) {
      console.warn('[ImportList] 清理预览图层失败:', e)
    } finally {
      facadePreviewLayer.value = null
    }
  }
  
  // 清理所有图层
  layers.forEach((layer, id) => {
    try {
      const map: any = (window as any).map
      if (map && map.removeLayer) {
        map.removeLayer(layer, true)
      }
    } catch (e) {
      console.warn(`[ImportList] 清理图层${id}失败:`, e)
    }
  })
  layers.clear()
})
</script>

<template>
  <div class="import-list">
    <div class="header-with-actions">
      <div class="title">已导入航线</div>
      <button class="btn-import-facade" @click="triggerFacadeKmlImport" title="导入立面KML">
        <span>📐</span> 立面
      </button>
    </div>
    <div v-if="items.length === 0" class="empty">暂无</div>
    <ul v-else class="list">
      <li v-for="item in items" :key="item.id" class="item">
        <div class="meta">
          <div class="name" :title="item.name">{{ item.name }}</div>
        </div>
        <!-- <div class="item-visibility">
          <span class="label">显示</span>
          <a-switch :checked="!!visibleMap[item.id]" @update:checked="onToggleItem(item.id, !!$event)" />
        </div> -->
        <div class="actions">
          <button class="btn" @click="open(item)">编辑</button>
          <!-- <button class="btn" @click="exportNormalKml(item)">导出KML</button>
          <button class="btn" @click="exportFlightKml(item)">飞控KML</button>
          <button class="btn" @click="exportDjiKmz(item)">KMZ</button> -->
          <button class="btn danger" @click="remove(item)">删除</button>
        </div>
      </li>
    </ul>

    <!-- 立面航线编辑器组件 -->
    <FacadeWaylineEditor
      :visible="showFacadeEditor"
      :segment="currentFacadeSegment"
      :params="facadeParams"
      @close="closeFacadeEditor"
      @generate="generateFacadeWayline"
      @update:params="facadeParams = $event"
    />
  </div>

</template>

<style scoped>
.import-list {
  position: absolute;
  z-index: 20;
  left: 10px;
  top: 60px;
  width: 360px;
  background: rgba(20,20,20,.65);
  backdrop-filter: saturate(150%) blur(4px);
  padding: 12px;
  border-radius: 10px;
  border: 1px solid rgba(255,255,255,.08);
  box-shadow: 0 8px 16px rgba(0,0,0,.25);
  color: #eaeaea;
}
.header-with-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.title { font-weight: 600; }
.btn-import-facade {
  padding: 4px 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 6px;
  color: #fff;
  font-size: 12px;
  cursor: pointer;
  transition: all .2s ease;
  display: flex;
  align-items: center;
  gap: 4px;
}
.btn-import-facade:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(102, 126, 234, 0.4);
}
.list {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 360px;
  overflow: auto;
}
.item {
  display: grid;
  grid-template-columns: 1fr auto auto;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-radius: 10px;
  border: 1px solid rgba(255,255,255,.08);
  background: rgba(255,255,255,.03);
  transition: background .2s ease, border-color .2s ease, transform .12s ease;
}
.item:hover { background: rgba(255,255,255,.06); border-color: rgba(255,255,255,.15); }
.meta { min-width: 0; }
.name { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.time { font-size: 12px; opacity: .7; margin-top: 2px; }
.item-visibility { display: flex; align-items: center; gap: 6px; }
.item-visibility .label { font-size: 12px; opacity: .85; }
.actions { margin-left: auto; display: flex; gap: 6px; flex-wrap: wrap; }
.btn {
  padding: 4px 8px;
  line-height: 1;
  color: #eaeaea;
  background: rgba(255,255,255,.04);
  border: 1px solid rgba(255,255,255,.08);
  border-radius: 6px;
  cursor: pointer;
  transition: all .15s ease;
}
.btn:hover { background: rgba(255,255,255,.08); border-color: rgba(255,255,255,.18); }
.btn.danger { color: #fff; background: rgba(217,83,79,.15); border-color: rgba(217,83,79,.35); }
.btn.danger:hover { background: rgba(217,83,79,.25); border-color: rgba(217,83,79,.55); }
.empty { opacity: .7; font-size: 12px; text-align: center; padding: 10px 0; }
</style>


